<!--
 * @description  : 市管-线路优化
 * @descriptionDetail: 市管-线路优化
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-07-09 18:43:02
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="false" :title="navTitle" :custom-back="handlerBack" style="z-index: 99999">
      <view class="nav-right-icon" @tap="handlerSure">
        确认
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="m-content">
      <view :style="{height: getContainerHeight()}" id="check-line-optimize-container"></view>
      <u-empty margin-top="10" style="justify-content: flex-start !important;" text="没有参与线路优化的检查户" mode="list" v-if="selectedChecks.length == 0"></u-empty>
      <view style="margin: 10rpx;" v-else @tap.stop.prevent>
        <draggable
          element="view"
          :sort="true"
          id="aaa"
          :delay="500"
          v-model="selectedChecks"
        >
          <view class="drag-item" v-for="(sc, idx) in selectedChecks" :key="idx">
            {{ sc.companyName }}{{ getDistanceXp(sc) }}
          </view>
        </draggable>
      </view>
    </view>
    <view class="preview-line1" @tap="handleCalculate">
      智能<br>排序
    </view>
    <view class="preview-line" @tap="handlerPreview">
      预览<br>路线
    </view>
  </view>
</template>

<script>
	import {
		AMapMixin
	} from '@/common/AMapMixin.js';
	import checkService from '@/service/check/check.service';
	import draggable from 'vuedraggable';
	import {
		SET_MAP_LAT_LON
	} from '@/config/setting.config.js';
	import fabButton from '@/components/uni-fab.vue';


	export default {
		components: {
			draggable,
			fabButton
		},
		mixins: [AMapMixin],
		data() {
			return {
				checkList: [], // 检查户
				selectedChecks: [], // 选中的检查户
				drag: false, // 拖拽
				retailerIcon: null, // 零售户icon
				retailerSelectIcon: null, // 零售户选中icon
				overlayGroups: [], // 覆盖物信息
				tmpSelecteds: undefined,
				newSelecteds: [],
				prvSelectList: [],
				nowDay: '',
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
			};
		},
		mounted() {
			this.setRightBtns();
			this.init();
		},
		onLoad(opt) {
			this.nowDay = opt.nowDay;
			this.$modal.showLoading('地图加载中...');
		},
		methods: {
			init() {
				this.retailerIcon = new AMap.Icon({
					size: new AMap.Size(24, 24), // 图标尺寸
					image: require('@/static/check/marker.png'), // Icon的图像
					imageSize: new AMap.Size(24, 24), //,
				});
				this.retailerSelectIcon = new AMap.Icon({
					size: new AMap.Size(24, 24), // 图标尺寸
					image: require('@/static/check/marker_selected.png'), // Icon的图像
					imageSize: new AMap.Size(24, 24), //,
				});
			},
			getDistanceXp(tmp) {
				if (tmp.distance) {
					return '[' + tmp.distance + '米]';
				}
				return '';
			},
			initAmap() {
				let self = this;
				// #ifndef H5-DINGDING || H5-WECHAT || H5-EMP
				self.curPos = SET_MAP_LAT_LON;
				self.setMapInstance(SET_MAP_LAT_LON);
				// #endif
				// #ifdef H5-DINGDING || H5-WECHAT || H5-EMP
        this.$deviceApi.geolocation().then(geo => {
          self.curPos = [geo.longitude, geo.latitude];
          self.setMapInstance([geo.longitude, geo.latitude]);
        }).catch(e => {
          console.log(e + JSON.stringify(e));
          this.$modal.toast("定位失败");
        });
				// this.getCurrentLocation().then(
				// 	(res) => {
				// 		self.curPos = [res.lng, res.lat];
				// 		self.setMapInstance([res.lng, res.lat]);
				// 	},
				// 	(err) => {
				// 		self.justInitMap();
				// 	}
				// );
				// #endif
			},
			setMapInstance() {
				this.curCords = new AMap.LngLat(this.curPos[0], this.curPos[1]);
				this.amap = new AMap.Map('check-line-optimize-container', {
					center: new AMap.LngLat(this.curPos[0], this.curPos[1]),
					zoom: 12,
					resizeEnable: true,
					scrollWheel: true,
					zoomEnable: true,
					// mapStyle: 'amap://styles/fresh',
				});
				this.$modal.hideLoading();
				this.setCurrentPointMarker();
				this.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Geolocation'], () => {
					this.amap.addControl(new AMap.ToolBar());
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					this.amap.addControl(new AMap.Scale());
				});
				this.queryCheckData();
			},
			justInitMap() {
				// this.$modal.alert("请在设备的设置中开启APP的定位权限后重新获取当前位置");
				this.amap = new AMap.Map('container', {
					showControlButton: true,
					zoom: 18,
					WebGLParams: {
						preserveDrawingBuffer: true,
					},
					resizeEnable: true, // 监控地图容器尺寸变化
					scrollWheel: true,
					zoomEnable: true,
				});
				this.$modal.hideLoading();
				this.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.Geolocation'], () => {
					this.amap.addControl(new AMap.ToolBar());
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					this.amap.addControl(new AMap.Scale());
				});
				this.queryCheckData();
			},
			getStatus(item) {
				if (!item.status && item.signStatus == '02') {
					return false;
				} else if (item.status == '02') {
					return false;
				} else if (item.status == '03') {
					return false;
				} else {
					return true;
				}
			},
			// 检查数据
			queryCheckData() {
				this.$u.loading('查询中...');
				this.checkList = [];
				let self = this;
				checkService.queryCheckClientListByCurrentDay({
					currentDate: this.nowDay,
					page: 1,
					limit: 999
				}).then((dr) => {
					this.$u.hideLoading();
					if (dr.success) {
						let tmpList = this.updateSortList(dr.data);
						this.checkList = tmpList.filter((c) => {
							return c.latitude && c.longitude && this.getStatus(c);
						});
						this.selectedChecks = [];
						this.prvSelectList = [];
						this.checkList.forEach((c) => {
							this.prvSelectList.push(c);
							this.selectedChecks.push(c);
						});
						let markers = [];
						this.prvSelectList.forEach((mg, idx) => {
							let markerConfig = {
								title: mg.companyName,
								icon: this.retailerSelectIcon,
								position: [mg.longitude, mg.latitude],
								offset: new AMap.Pixel(-8, 5),
								label: {},
							};
							if (idx < 30) {
								markerConfig.label = {
									content: mg.companyName,
									offset: new AMap.Pixel(26, 1),
								};
							}
							let marker = new AMap.Marker(markerConfig);
							marker.retailer = mg;
							marker.on('click', (m) => {
								let sChecks = self.prvSelectList.filter((sc) => sc.retailerUuid == m.target.retailer.retailerUuid);
								if (sChecks.length > 0) {
									m.target.setIcon(self.retailerIcon);
									self.prvSelectList = self.prvSelectList.filter((sc) => sc.retailerUuid != m.target.retailer.retailerUuid);
								} else {
									m.target.setIcon(self.retailerSelectIcon);
									self.prvSelectList.push(m.target.retailer);
								}
							});
							markers.push(marker);
						});
						this.amap.clearMap();
						this.overlayGroups = new AMap.OverlayGroup(markers);
						this.amap.add(this.overlayGroups);
						this.amap.setFitView();
					} else {
						this.$u.toast(dr.msg);
					}
				});
			},
			updateSortList(list) {
				let sortApr = this.$storage.get(this.$rp.check.SORT);
				sortApr = sortApr == '' ? {} : sortApr;
				let sortDate = sortApr.sortDate || '';
				let sortList = sortApr.sortData || [];
				if (sortList.length == 0 || sortDate != this.nowDay) {
					// 为空或者日期不对的检查列表数据不排序
					return list;
				} else {
					let otherList = list.filter((it) => !sortList.includes(it.checkUuid));
					let realList = list.filter((it) => sortList.includes(it.checkUuid));
					let rList = [];
					sortList.forEach((itm) => {
						for (let i = 0; i < realList.length; i++) {
							if (realList[i].checkUuid == itm) {
								rList.push(realList[i]);
								break;
							}
						}
					});
					rList = [...rList, ...otherList];
					let signList = rList.filter((ip) => {
						return ip.status != '02' && ip.signStatus == '02'; // 如果是已签到
					});
					let ipArr = [];
					signList.forEach((ixp) => {
						ipArr.push(ixp.checkUuid);
					});
					let finishList = rList.filter((ip) => {
						return ip.status == '02'; // 如果是已完成
					});
					finishList.forEach((ixp) => {
						ipArr.push(ixp.checkUuid);
					});
					let unSignList = rList.filter((ix) => {
						return !ipArr.includes(ix.checkUuid);
					});
					rList = [...signList, ...unSignList, ...finishList];
					return rList;
				}
			},
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight('确定', () => {
					this.handlerSure();
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.handlerSure();
				}
			},
			getContainerHeight() {
				let p = (this.$u.sys().windowHeight - 44 - this.$u.sys().statusBarHeight) / 2 + 'px';
				// #ifdef H5-DINGDING
				p = (this.$u.sys().windowHeight - this.$u.sys().statusBarHeight) / 2 + 'px';
				// #endif
				return p;
			},
			getContainerWidth() {
				return this.$u.sys().windowWidth + 'px';
			},
			handlerBack() {
				this.amap && this.amap.destroy();
				this.backPrev({
					paramKey: 'refresh',
					param: true
				});
			},
			// 拖拽结束
			handlerDragEnd(a, b, c) {
				console.log('拖拽结束', a, b, c);
				console.log(this.selectedChecks);
			},
			// 确定操作
			handlerSure() {
				if (this.selectedChecks.length == 0) {
					this.$u.toast('请选择零售户进行线路优化');
					return;
				}
				this.hanlerSave();
			},
			// 保存操作
			hanlerSave() {
				let dayUuids = [];
				let sortUuids = [];
				this.selectedChecks.forEach((sc, idx) => {
					sortUuids.push(sc.checkUuid);
				});
				this.backPrev({
					paramKey: 'sort',
					param: sortUuids,
				});
			},
			// 预览路线
			handlerPreview() {
				if (this.prvSelectList.length < 3) {
					this.$u.toast('请选择两个以上零售户');
					return;
				}
				if (this.prvSelectList.length > 17) {
					this.$u.toast('高德地图目前最多支持16个途径点');
					return;
				}
				let linePoints = [{
					lng: this.curPos[0],
					lat: this.curPos[1],
					name: '我的位置'
				}];
				this.prvSelectList.forEach((sc) => linePoints.push({
					lng: sc.longitude,
					lat: sc.latitude,
					name: sc.companyName
				}));
				this.setRouteParam(linePoints);
				this.$u.route('/pages/check/viewLine');
			},
			handleCalculate() {
				this.$modal.confirm(
					'地图服务实时测距排序',
					'提示',
					() => {
						this.calculateDistanceAndSort(1);
					},
					() => {
						this.calculateDistanceAndSort(3);
					},
					'驾车',
					'步行'
				);
			},
			calculateDistanceAndSort(type) {
				if (this.selectedChecks.length <= 1) {
					this.$u.toast('不需要计算排序');
					return;
				}
				if (this.curPos == undefined || this.curPos.length != 2) {
					this.$u.toast('当前位置获取失败,稍后重试');
					this.getCurrentLocation().then(
						(res) => {
							this.curPos = [res.lng, res.lat];
						},
						(err) => {}
					);
					return;
				}
				this.$modal.showLoading('正在计算' + (type == 1 ? '驾车' : '步行') + '距离并排序...');
				this.tmpSelecteds = this.$u.deepClone(this.selectedChecks);
				this.newSelecteds = [];
				this.getDistance(this.curPos.join(','), this.tmpSelecteds, type);
			},
			// 距离测量
			// type  1 驾车  3 步行
			getDistance(desNow, checkLists, type) {
				let self = this;
				const SERVER_KEY = process.uniEnv.AMAP.SERVER_KEY;
				let arr = checkLists.map(({
					latitude,
					longitude
				}) => {
					return `${longitude},${latitude}`;
				});
				this.getCurDistance({
						destination: desNow,
						key: SERVER_KEY, // 很重要，不能删，占位置
						origins: arr.join('|'),
						output: 'JSON',
						type: type,
					})
					.then((rs) => {
						let sortTmp = this.$u.deepClone(rs);
						rs.sort((a, b) => {
							return a.distance - b.distance;
						});
						let pos = -1;
						for (let i = 0; i < sortTmp.length; i++) {
							if (sortTmp[i].origin_id == rs[0].origin_id) {
								pos = i;
								break;
							}
						}
						let tmp = this.tmpSelecteds.splice(pos, 1)[0];
						this.$set(tmp, 'distance', rs[0].distance);
						this.newSelecteds.push(tmp);
						if (this.tmpSelecteds.length > 0) {
							this.getDistance([tmp.longitude, tmp.latitude].join(','), this.tmpSelecteds, type);
						} else {
							this.$modal.hideLoading();
							this.selectedChecks = [...this.newSelecteds];
						}
					})
					.catch((e) => {
						this.$modal.hideLoading();
						this.$u.toast('排序失败');
					});
			},
		},
	};
</script>

<style scoped lang="scss">
	#check-line-optimize-container {
		width: 100%;
		height: 50%;
	}

	.drag-item {
		padding: 8px 10px;
		border-bottom: 1px solid #eee;
	}

	.preview-line1 {
		width: 60px;
		height: 60px;
		text-align: center;
		color: #fff;
		background-color: #2979ff;
		border-radius: 50%;
		padding: 10px;
		font-size: 14px;
		position: fixed;
		bottom: 80px;
		right: 10px;
	}

	.preview-line {
		width: 60px;
		height: 60px;
		text-align: center;
		color: #fff;
		background-color: #2979ff;
		border-radius: 50%;
		padding: 10px;
		font-size: 14px;
		position: fixed;
		bottom: 10px;
		right: 10px;
	}
</style>
